package cn.nxcoder.blog.controller;

import cn.nxcoder.blog.entity.Blog;
import cn.nxcoder.blog.entity.Tag;
import cn.nxcoder.blog.entity.Type;
import cn.nxcoder.blog.entity.User;
import cn.nxcoder.blog.exception.NonBlogException;
import cn.nxcoder.blog.model.BlogVo;
import cn.nxcoder.blog.model.Page;
import cn.nxcoder.blog.service.BlogService;
import cn.nxcoder.blog.service.TagService;
import cn.nxcoder.blog.service.TypeService;
import cn.nxcoder.blog.service.UserService;
import cn.nxcoder.blog.util.MarkdownUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author shengwu ni
 * @date 2018/05/03 20:30
 */
@Controller
public class IndexController {

    @Resource
    private BlogService blogService;
    @Resource
    private TypeService typeService;
    @Resource
    private TagService tagService;
    @Resource
    private UserService userService;

    @GetMapping("/")
    public String index(@RequestParam(defaultValue = "1") Integer page, Model model) {

        // 每页显示8条记录
        PageHelper.startPage(page, 8);
        // 根据条件查出8条记录
        List<Blog> blogList = blogService.findAllByCreateTimeDesc();
//        Page<Blog> pageInfo = new Page<>(blogList);
//        List<BlogVo> blogInfoList = getBlogInfoList(blogList);
//        pageInfo.setBlogList(blogInfoList);

        PageInfo pageInfo = new PageInfo(blogList);

//        // 查询出6条博客类型数据（按照包含博客数量多少降序）
//        List<Type> typeList = typeService.findAllTypes();
//        // 查询出10条博客标签数据（按照包含博客数量多少降序）
//        List<Tag> tagList = tagService.findAllTags();
//        // 查询出访问量最多的5条记录
//        List<Blog> topView = blogService.findTop5Views();

        model.addAttribute("page", pageInfo);
//        model.addAttribute("types", typeList);
//        model.addAttribute("tags", tagList);
//        model.addAttribute("views", topView);
//        model.addAttribute("total", blogService.findAll().size());
        model.addAttribute("title", "首页");
        return "index";
    }

    @GetMapping("/blog")
    public String blog() {
        return "blog";
    }

    private List<BlogVo> getBlogInfoList(List<Blog> list) {

        List<BlogVo> blogInfoList = new ArrayList<>();

        // 封装信息
        if (list != null && list.size() > 0) {
            list.forEach((b) -> {
                BlogVo blogVo = new BlogVo();
                BeanUtils.copyProperties(b, blogVo);
                blogVo.setUpdate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(b.getUpdateTime()));
                blogVo.setCreate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(b.getCreateTime()));

                // 封装type信息
                Long typeid = b.getTypeid();
                if (typeid != null) {
                    Type type = typeService.findById(typeid);
                    blogVo.setType(type);
                }

                // 封装user信息
                Long userid = b.getUserid();
                User user = userService.findById(userid);
                blogVo.setUser(user);

                // 封装tag信息
                List<Tag> tags = new ArrayList<>();
                String tagids = b.getTagid();
                String[] tagArr = tagids.split(",");
                if (tagArr != null && tagArr.length > 0) {
                    for (String tagid : tagArr) {
                        if (tagid != null && !"".equals(tagid)) {
                            Tag tag = tagService.findById(Long.valueOf(tagid));
                            tags.add(tag);
                        }
                    }
                }
                blogVo.setTags(tags);

                blogInfoList.add(blogVo);
            });
        }
        return blogInfoList;
    }

    @PostMapping("/search")
    public String search(@RequestParam(defaultValue = "1") Integer page,
                         @RequestParam String query, Model model) {

        // 每页显示8条记录
        PageHelper.startPage(page, 8);
        // 根据条件查出8条记录
        List<Blog> blogList = findBlogsByQuery(query);
        Page<Blog> pageInfo = new Page<>(blogList);
        List<BlogVo> blogInfoList = getBlogInfoList(blogList);
        pageInfo.setBlogList(blogInfoList);
        model.addAttribute("page", pageInfo);
        model.addAttribute("query", query);
        model.addAttribute("title", "搜索结果");
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {

        Blog blog = blogService.findById(id);
        if (blog == null) {
            throw new NonBlogException("该博客不存在，可能已经被作者删除，或者放到草稿箱。");
        }
        // 更新一下访问量
        blog.setViews(blog.getViews() + 1);
        blogService.update(blog);
        // 先将emoji表情还原
        blog.setContent(EmojiParser.parseToUnicode(blog.getContent()));
        // 将博客内容的markdown转成html
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(blog.getContent()));

        BlogVo blogVo = new BlogVo();
        BeanUtils.copyProperties(blog, blogVo);
        blogVo.setCreate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(blog.getCreateTime()));

        // 封装type信息
        Long typeid = blog.getTypeid();
        Type type = typeService.findById(typeid);
        blogVo.setType(type);

        // 封装tag信息
        String tagid = blog.getTagid();
        List<Tag> tags = new ArrayList<>();
        if (tagid != null && !"".equals(tagid)) {
            String[] tagids = tagid.split(",");
            for (String tagId : tagids) {
                Tag tag = tagService.findById(Long.valueOf(tagId));
                tags.add(tag);
            }
        }
        blogVo.setTags(tags);

        // 封装user信息
        Long userid = blog.getUserid();
        User user = userService.findById(userid);
        blogVo.setUser(user);

        model.addAttribute("blog", blogVo);
        model.addAttribute("title", blogVo.getTitle());
        return "blog";
    }

    private List<Blog> findBlogsByQuery(String query) {

        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("published", 1);
        criteria.andLike("title", "%" + query + "%");
        criteria.orLike("content", "%" + query + "%");
        List<Blog> blogList = blogService.selectByExample(example);
        return blogList;
    }
}
